import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { CommentService } from '../services/CommentService';
import { PostService } from '../services/PostService';
import { usePost } from '../contexts/PostContext';
import { useAuth } from '../../auth/AuthContext';
import { Post, Comment } from '../types';
import {
  Box,
  IconButton,
  Paper,
  Typography,
  TextField,
  Button,
  CircularProgress,
  Alert,
  Grid,
  Modal,
  Card,
  CardContent,
  CardActions,
  Avatar,
  Divider,
  Snackbar
} from '@mui/material';
import { Delete as DeleteIcon, Edit as EditIcon, Comment as CommentIcon, Close as CloseIcon } from '@mui/icons-material';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface PostListProps {
  userId?: number;
  onEditPost?: (postId: number) => void;
}

export const PostList = forwardRef<{ handleOpenModal: (post: Post) => void }, PostListProps>(({ userId, onEditPost }, ref) => {
  const { posts, loading, error, fetchPosts, fetchUserPosts, deletePost, updatePostComments } = usePost();
  const { user } = useAuth();
  const [newComment, setNewComment] = useState('');
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [commentLoading, setCommentLoading] = useState(false);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');

  useEffect(() => {
    // 添加一个标志，避免重复获取数据
    let isMounted = true;
    
    const loadData = async () => {
      if (userId) {
        await fetchUserPosts(userId);
      } else {
        await fetchPosts();
      }
    };
    
    if (isMounted) {
      loadData();
    }
    
    // 清理函数
    return () => {
      isMounted = false;
    };
    // 只在组件挂载时和 userId 变化时获取数据
  }, [userId]);

  const handleAddComment = async (postId: number) => {
    if (!newComment.trim() || !user) return;

    setCommentLoading(true);
    try {
      const newCommentData = await CommentService.addComment(postId, newComment);
      
      // 使用服务器返回的评论数据，而不是创建新对象
      // 使用 updatePostComments 方法更新帖子的评论列表
      updatePostComments(postId, newCommentData);
      
      // 更新选中的帖子，以便在模态框中显示最新评论
      if (selectedPost) {
        setSelectedPost({
          ...selectedPost,
          comments: [...(selectedPost.comments || []), newCommentData],
          commentCount: (selectedPost.commentCount || 0) + 1
        });
      }
      
      setNewComment('');
      
      // 显示成功消息
      setSnackbarMessage('评论发表成功！');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
    } catch (error) {
      console.error('添加评论失败:', error);
      // 显示错误消息
      setSnackbarMessage('评论发表失败，请稍后重试');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    } finally {
      setCommentLoading(false);
    }
  };

  const handleDelete = async (postId: number) => {
    if (window.confirm('确定要删除这个帖子吗？')) {
      try {
        await deletePost(postId);
        if (selectedPost?.postId === postId) {
          setModalOpen(false);
          setSelectedPost(null);
        }
        // 显示删除成功消息
        setSnackbarMessage('帖子已成功删除！');
        setSnackbarSeverity('success');
        setSnackbarOpen(true);
      } catch (error) {
        console.error('删除帖子失败:', error);
        // 显示删除失败消息
        setSnackbarMessage('删除帖子失败，请重试！');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
      }
    }
  };

  const handleDeleteComment = async (commentId: number, postId: number) => {
    if (window.confirm('确定要删除这条评论吗？')) {
      try {
        await CommentService.deleteComment(commentId);
        
        // 更新帖子的评论列表
        if (selectedPost) {
          const updatedComments = selectedPost.comments?.filter(comment => comment.commentId !== commentId) || [];
          setSelectedPost({
            ...selectedPost,
            comments: updatedComments,
            commentCount: updatedComments.length
          });
        }
        
        // 更新PostContext中的帖子数据
        if (updatePostComments) {
          await updatePostComments(postId);
        }
        
        // 显示删除成功消息
        setSnackbarMessage('评论已成功删除！');
        setSnackbarSeverity('success');
        setSnackbarOpen(true);
      } catch (error) {
        console.error('删除评论失败:', error);
        // 显示删除失败消息
        setSnackbarMessage('删除评论失败，请重试！');
         setSnackbarSeverity('error');
         setSnackbarOpen(true);
      }
    }
  };

  const handleOpenModal = async (post: Post) => {
    try {
      console.log('正在获取帖子详情，包括评论数据...');
      // 调用PostService.getPostById获取包含评论的完整帖子数据
      const fullPost = await PostService.getPostById(post.postId);
      setSelectedPost(fullPost);
      setModalOpen(true);
    } catch (error) {
      console.error('获取帖子详情失败:', error);
      // 如果获取失败，仍然显示原始帖子数据
      setSelectedPost(post);
      setModalOpen(true);
    }
  };
  
  // 暴露 handleOpenModal 方法给父组件
  useImperativeHandle(ref, () => ({
    handleOpenModal
  }));

  const handleCloseModal = () => {
    setModalOpen(false);
    setSelectedPost(null);
    setNewComment('');
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Alert severity="error" sx={{ mt: 2 }}>
        {error}
      </Alert>
    );
  }

  if (!posts) {
    return (
      <Alert severity="warning" sx={{ mt: 2 }}>
        数据加载异常
      </Alert>
    );
  }

  if (posts.length === 0) {
    return (
      <Alert severity="info" sx={{ mt: 2 }}>
        {userId ? '该用户暂无帖子' : '暂无帖子'}
      </Alert>
    );
  }

  // 截取内容的辅助函数
  const truncateContent = (content: string, maxLength: number = 100) => {
    if (!content) return '无内容';
    if (content.length <= maxLength) return content;
    return content.substring(0, maxLength) + '...';
  };

  return (
    <>
      <Grid container spacing={3} sx={{ maxWidth: '100%', mx: 'auto', mt: 4 }}>
        {posts.map((post) => (
          <Grid item xs={12} sm={6} md={3} key={post.postId}>
            <Card 
              elevation={2} 
              sx={{ 
                height: '100%', 
                display: 'flex', 
                flexDirection: 'column',
                transition: 'transform 0.2s, box-shadow 0.2s',
                '&:hover': {
                  transform: 'translateY(-4px)',
                  boxShadow: 6
                },
                cursor: 'pointer'
              }}
              onClick={() => handleOpenModal(post)}
            >
              <CardContent sx={{ flexGrow: 1 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                  <Avatar sx={{ mr: 1, bgcolor: 'primary.main' }}>
                    {post.user?.username ? post.user.username.charAt(0).toUpperCase() : '?'}
                  </Avatar>
                  <Box>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                      {post.user?.username || '未知用户'}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      {post.postTime && !isNaN(new Date(post.postTime).getTime()) 
                        ? formatDistanceToNow(new Date(post.postTime), { addSuffix: true, locale: zhCN })
                        : '刚刚'}
                    </Typography>
                  </Box>
                </Box>
                <Divider sx={{ mb: 2 }} />
                <Typography variant="h6" sx={{ mb: 1, fontWeight: 'bold' }}>
                  {post.postTitle || '无标题'}
                </Typography>
                <Typography variant="body2" color="text.primary" sx={{ mb: 2, minHeight: '60px' }}>
                  {truncateContent(post.postContent)}
                </Typography>
              </CardContent>
              <CardActions sx={{ justifyContent: 'flex-end', px: 2, pb: 2 }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <IconButton size="small" color="primary">
                    <CommentIcon fontSize="small" />
                  </IconButton>
                  <Typography variant="caption">{post.commentCount || 0}</Typography>
                </Box>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>

      {/* 帖子详情模态框 */}
      <Modal
        open={modalOpen}
        onClose={handleCloseModal}
        aria-labelledby="post-detail-modal"
        aria-describedby="post-detail-and-comments"
      >
        <Box sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: { xs: '90%', sm: '80%', md: '70%', lg: '60%' },
          maxHeight: '90vh',
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4,
          borderRadius: 2,
          overflow: 'auto'
        }}>
          {selectedPost && (
            <>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 3 }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Avatar sx={{ mr: 2, bgcolor: 'primary.main' }}>
                    {selectedPost.user?.username ? selectedPost.user.username.charAt(0).toUpperCase() : '?'}
                  </Avatar>
                  <Box>
                    <Typography variant="h6">{selectedPost.user?.username || '未知用户'}</Typography>
                    <Typography variant="caption" color="text.secondary">
                      {selectedPost.postTime && !isNaN(new Date(selectedPost.postTime).getTime()) 
                        ? formatDistanceToNow(new Date(selectedPost.postTime), { addSuffix: true, locale: zhCN })
                        : '刚刚'}
                    </Typography>
                  </Box>
                </Box>
                <Box sx={{ display: 'flex', gap: 1 }}>
                  {user?.id && Number(user.id) === selectedPost.user?.userId && (
                    <>
                      <IconButton
                        onClick={(e) => {
                          e.stopPropagation();
                          onEditPost?.(selectedPost.postId);
                          handleCloseModal();
                        }}
                        color="primary"
                        size="small"
                      >
                        <EditIcon />
                      </IconButton>
                      <IconButton
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(selectedPost.postId);
                        }}
                        color="error"
                        size="small"
                      >
                        <DeleteIcon />
                      </IconButton>
                    </>
                  )}
                  <IconButton onClick={handleCloseModal} size="small">
                    <CloseIcon />
                  </IconButton>
                </Box>
              </Box>

              <Paper 
                elevation={0} 
                sx={{ 
                  p: 3, 
                  mb: 4, 
                  backgroundColor: '#f8f9fa',
                  border: '1px solid #e0e0e0',
                  borderRadius: 2,
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-word'
                }}
              >
                <Typography variant="h5" sx={{ mb: 2, fontWeight: 'bold' }}>
                  {selectedPost.postTitle || '无标题'}
                </Typography>
                <Typography variant="body1">
                  {selectedPost.postContent || '无内容'}
                </Typography>
              </Paper>

              <Divider sx={{ mb: 3 }} />
              
              <Typography variant="h6" sx={{ mb: 2 }}>
                评论 ({selectedPost.commentCount || 0})
              </Typography>
              
              <Box sx={{ mb: 3 }}>
                {selectedPost.comments?.length > 0 ? (
                  selectedPost.comments.map((comment: Comment) => (
                    <Paper key={comment.commentId} variant="outlined" sx={{ p: 2, mb: 2 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                        <Typography variant="subtitle2">
                          {comment.username}
                        </Typography>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <Typography variant="caption" color="text.secondary">
                            {comment.commentTime && !isNaN(new Date(comment.commentTime).getTime())
                              ? formatDistanceToNow(new Date(comment.commentTime), { addSuffix: true, locale: zhCN })
                              : '刚刚'}
                          </Typography>
                          {user && comment.userId === Number(user.id) && (
                            <IconButton
                              size="small"
                              onClick={() => handleDeleteComment(comment.commentId, selectedPost.postId)}
                              sx={{ color: 'error.main' }}
                            >
                              <DeleteIcon fontSize="small" />
                            </IconButton>
                          )}
                        </Box>
                      </Box>
                      <Typography variant="body2" color="text.primary">
                        {comment.commentContent}
                      </Typography>
                    </Paper>
                  ))
                ) : (
                  <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', py: 2 }}>
                    暂无评论，来发表第一条评论吧
                  </Typography>
                )}
              </Box>
              
              {user && (
                <Box sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    multiline
                    rows={3}
                    value={newComment}
                    onChange={(e) => setNewComment(e.target.value)}
                    placeholder="写下你的评论..."
                    variant="outlined"
                    sx={{ mb: 2 }}
                    disabled={commentLoading}
                  />
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button
                      onClick={() => handleAddComment(selectedPost.postId)}
                      variant="contained"
                      color="primary"
                      disabled={!newComment.trim() || commentLoading}
                    >
                      {commentLoading ? '发表中...' : '发表评论'}
                    </Button>
                  </Box>
                </Box>
              )}
            </>
          )}
        </Box>
      </Modal>

      {/* 消息提示 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </>
  );
});

export default PostList;